﻿using FastReport.Export.PdfSimple;
using FastReport.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace QMERP.Infrastructure.Tools
{
    public static class PdfUtils
    {
        /// <summary>
        /// 根据模版生成Pdf流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="form"></param>
        /// <param name="t"></param>
        //public static MemoryStream GetStreamByTemplatePath<T>(string path, List<T> initializeData, string initializeDataName) where T : class
        //{
        //    MemoryStream stream = new();
        //    WebReport report = new();
        //    report.Report.Load(path);
        //    report.Report.RegisterData(initializeData, initializeDataName);
        //    report.Report.Prepare();
        //    PDFSimpleExport export = new PDFSimpleExport();
        //    report.Report.Export(export, stream);
        //    return stream;
        //}
        /// <summary>
        /// 合并pdf
        /// </summary>
        /// <param name="fileList">要合并的pdf文件流</param>
        /// <param name="outMergeFile">输出文件全路径</param>
        public static MemoryStream MergePdf(List<MemoryStream> streams)
        {
            MemoryStream pdfStream = new();
            using (var document = new Document())
            {
                using var pdf = new PdfCopy(document, pdfStream);
                document.Open();
                streams.ForEach(stream =>
                {
                    stream.Position = 0;
                    var reader = new PdfReader(stream);
                    for (int i = 0; i < reader.NumberOfPages; i++)
                    {
                        var page = pdf.GetImportedPage(reader, i + 1);
                        pdf.AddPage(page);
                    }
                    pdf.FreeReader(reader);
                    reader.Close();
                });
            }
            return pdfStream;
        }
    }
}
